package com.ruoyi.web.controller.module.estate;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDate;
import java.time.Month;
import java.time.Year;
import java.util.*;

import cn.hutool.core.util.ObjectUtil;
import com.ruoyi.system.domain.module.property.*;
import com.ruoyi.system.domain.module.wx.WxUser;
import com.ruoyi.system.service.module.ISmsTemplateService;
import com.ruoyi.system.service.module.estate.*;
import com.ruoyi.system.service.module.property.*;
import com.ruoyi.system.service.module.wx.IWxUserService;
import com.ruoyi.web.controller.common.BaseController;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.PageUtils;
import com.ruoyi.common.utils.QRCodeUtilEx;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.system.domain.module.estate.*;
import com.ruoyi.system.domain.module.product.ProductRule;
import com.ruoyi.system.domain.module.product.ProductRuleRelation;
import com.ruoyi.system.domain.module.excel.PropertyWaterTemplateExcel;
import lombok.RequiredArgsConstructor;

import javax.validation.constraints.*;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.parameters.P;
import org.springframework.web.bind.annotation.*;
import org.springframework.validation.annotation.Validated;
import com.ruoyi.common.annotation.RepeatSubmit;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.validate.AddGroup;
import com.ruoyi.common.core.validate.EditGroup;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

/**
 * 小区内的房屋列信息Controller
 *
 * @author ruoyi
 * @date 2022-07-08
 */
@Validated
@Api(value = "小区内的房屋列信息控制器", tags = {"小区内的房屋列信息管理"})
@RequiredArgsConstructor(onConstructor_ = @Autowired)
@RestController
@RequestMapping("/module/estate/room")
public class EstateRoomController extends BaseController {

	private final IEstateRoomService estateRoomService;
	private final IEstateBuildUnitService estateBuildUnitService;
	private final IEstateBuildFloorService estateBuildFloorService;
	private final IEstateService estateService;
	private final IPropertyFeeOrderTemplateService propertyFeeOrderTemplateService;
	private final IEstateCallCenterRecordService estateCallCenterRecordService;
	private final IEstateCallCenterService estateCallCenterService;
	private final IEstateRoomAccountRecordService estateRoomAccountRecordService;
	private final IPropertyFeeOrderService propertyFeeOrderService;
	private final IPropertyFeeOrderInfoService propertyFeeOrderInfoService;
	private final IPropertyService propertyService;
	private final IWxUserService wxUserService;
	private final IEstateRoomBangUserService estateRoomBangUserService;
	private final IPropertyFeeOrderTemplateApproverService propertyFeeOrderTemplateApproverService;
	private final IPropertyFeeOrderTemplateApproverInfoService propertyFeeOrderTemplateApproverInfoService;

	private final ISmsTemplateService smsTemplateService;

	@Value("${ruoyi.profile}")
	private String uploadPath;

	@Value("${ruoyi.imgUrl}")
	private String imgUrl;

	/**
	 * 查询小区内的房屋列信息列表
	 */
	@ApiOperation("查询小区内的房屋列信息列表")
	@PreAuthorize("@ss.hasPermi('module:estateRoom:list')")
	@GetMapping("/list")
	public TableDataInfo<EstateRoom> list(@Validated EstateRoom estateRoom) {
		SysUser sysUser = getUser();
		QueryWrapper<EstateRoom> qw = new QueryWrapper<>();

		if (sysUser.getUserType() < 2) {
			if (estateRoom.getEstateId() != null) {
				qw.eq("estate_id", estateRoom.getEstateId());
			}
		} else if (sysUser.getUserType() == 2) {
			if (sysUser.getEstateId() != null && estateRoom.getEstateId() != null) {
				qw.eq("estate_id", sysUser.getEstateId());
			} else if (sysUser.getEstateId() == null && estateRoom.getEstateId() == null) {
				QueryWrapper qwEstate = new QueryWrapper<>();
				qwEstate.eq("property_id", sysUser.getPropertyId());
				List<Estate> estates = estateService.list(qwEstate);
				for (Estate estate : estates) {
					qw.or().eq("estate_id", estate.getId());
				}
			} else if (sysUser.getEstateId() == null && estateRoom.getEstateId() != null) {
				qw.eq("estate_id", estateRoom.getEstateId());
			}
		} else if (sysUser.getUserType() == 3) {
			qw.eq("estate_id", sysUser.getEstateId());
		}
		if (estateRoom.getRoomNum() != null) {
			qw.like("room_num", estateRoom.getRoomNum());
		}
		if (estateRoom.getUnitNo() != null) {
			qw.like("unit_no", estateRoom.getUnitNo());
		}
		if (estateRoom.getBuildNo() != null) {
			qw.like("build_no", estateRoom.getBuildNo());
		}
//		if(estateRoom.getRoomNo()!=null){
//			qw.and(wrapper->{
//				wrapper.like("room_no", estateRoom.getRoomNo());
//			});
//		}

		if (estateRoom.getRealName() != null) {
			qw.and(wrapper -> {
				wrapper.like("real_name", estateRoom.getRealName())
					.or().like("phone_num", estateRoom.getRealName())
					.or().like("room_no", estateRoom.getRealName());
			});
		}
		qw.orderByAsc("room_no");
		TableDataInfo<EstateRoom> td = PageUtils.buildDataInfo(estateRoomService.page(PageUtils.buildPage(), qw));
		List<EstateRoom> list = td.getRows();
		if (CollUtil.isNotEmpty(list)) {
			for (EstateRoom room : list) {
				if (StrUtil.isNotEmpty(room.getQrCode())) {
					room.setQrCode(imgUrl + room.getQrCode());
				}
				//查询缴费至几月
				if (room.getId() != null) {
					QueryWrapper<PropertyFeeOrderTemplate> qw1 = new QueryWrapper<>();
					qw1.eq("room_id", room.getId());
					qw1.eq("state", 0);
					qw1.last("limit 1");
					List<PropertyFeeOrderTemplate> template = propertyFeeOrderTemplateService.list(qw1);
					if (template.size() > 0) {
						String year = template.get(0).getYearNum();
						String month = template.get(0).getMonthNum();
						room.setPaymentTo("至" + year + "年" + month + "月");
					}
				}
			}
		}
		/*if(estateRoom.getQianfei()==0){*/
           /* QueryWrapper<PropertyFeeOrderTemplate> qw1=new QueryWrapper<>();
            qw1.eq("year_num",2022).or()
                    .le("month_num",9).or().eq("state",0);
            List<PropertyFeeOrderTemplate> list1=propertyFeeOrderTemplateService.list(qw1);
            for  (int i = 0;i < list1.size()- 1;i++)  {
                for  (int j = list1.size() - 1;j > i;j--)  {
                    if  (list1.get(j).getRoomNo().equals(list1.get(i).getRoomNo()))  {
                        list1.remove(j);
                    }
                }
            }
            for  (int i = 0;i < list1.size()- 1;i++)  {
                for  (int j = list.size() - 1;j > i;j--)  {
                    if  (list.get(j).getRoomNo().equals(list1.get(i).getRoomNo()))  {
                        list.remove(j);
                    }
                }
            }*/
		/*}*/
		/*System.out.println(estateRoom.getQianfei()==0);*/
		return td;
	}

	/**
	 * 查询 业主信息
	 */
	@ApiOperation("通过手机号查询业主信息")
	@PreAuthorize("@ss.hasPermi('module:estateRoom:query')")
	@GetMapping("/getUserData/{phone}")
	public AjaxResult<EstateRoom> getUserData(@NotNull(message = "主键不能为空") @PathVariable("phone") String phone) {
		EstateRoom estateRoom = new EstateRoom();
		SysUser sysUser = getUser();
		QueryWrapper<EstateRoom> qw = new QueryWrapper<>();
		qw.like("phone_num", phone);
		List<EstateRoom> estateRooms = estateRoomService.list(qw);
		if (estateRooms.size() > 0) {
			estateRoom = estateRooms.get(0);
		} else {
			if (sysUser.getEstateId() != null) {
				estateRoom.setEstateId(sysUser.getEstateId());
			} else {
				estateRoom.setEstateId(1);
			}

			estateRoom.setRoomNo("非本小区业主");
			estateRoom.setPhoneNum(phone);
			estateRoom.setRealName("非本小区业主");
		}
		//添加通话记录
		EstateCallCenterRecord record = new EstateCallCenterRecord();
		if (estateRoom.getEstateId() != null) {
			record.setEstateId(estateRoom.getEstateId());
			EstateCallCenter call = estateCallCenterService.selectByUniqueColumn("estate_id", estateRoom.getEstateId());
			if (call != null) {
				record.setCenterId(call.getId());
				record.setCenterName(call.getCenterName());
			}
		}
		if (estateRoom.getRoomNo() != null) {
			record.setRoomNo(estateRoom.getRoomNo());
		}
		if (estateRoom.getRealName() != null) {
			record.setRealName(estateRoom.getRealName());
		}
		record.setState(0);
		record.setCallPhone(phone);
		//判断该记录是否已被录入
		QueryWrapper<EstateCallCenterRecord> qwCall = new QueryWrapper<>();
		Date beginDate = new Date();
		Date endDate = new Date();
		beginDate.setTime(beginDate.getTime() - 180000);
		qwCall.between("create_time", beginDate, endDate);
		qwCall.eq("call_phone", phone);
		qwCall.eq("state", 0);
		List<EstateCallCenterRecord> list = estateCallCenterRecordService.list(qwCall);
		if (list.size() == 0) {
			estateCallCenterRecordService.save(record);
		}
		return AjaxResult.success(estateRoom);
	}

	/**
	 * 查询小区业主数量
	 */
	@ApiOperation("查询小区业主数量")
	@PreAuthorize("@ss.hasPermi('module:estateRoom:query')")
	@GetMapping("/getRoomNum")
	public int roomNum() {
		SysUser sysUser = getUser();
		Integer num = 0;
		if (sysUser.getUserType() == 2) {
			if (sysUser.getEstateId() == null) {
				QueryWrapper<Estate> qw1 = new QueryWrapper<>();
				if (sysUser.getPropertyId() != null) {
					qw1.eq("property_id", sysUser.getPropertyId());
				}
				List<Estate> estates = estateService.list(qw1);
				for (Estate estate : estates) {
					QueryWrapper<EstateRoom> qw = new QueryWrapper<>();
					if (estate.getId() != null) {
						qw.eq("estate_id", estate.getId());
					}
					TableDataInfo<EstateRoom> td = PageUtils.buildDataInfo(estateRoomService.page(PageUtils.buildPage(), qw));
					List<EstateRoom> list = td.getRows();
					num += list.size();
				}
			} else {
				QueryWrapper<EstateRoom> qw = new QueryWrapper<>();
				if (sysUser.getEstateId() != null) {
					qw.eq("estate_id", sysUser.getEstateId());
				}
				TableDataInfo<EstateRoom> td = PageUtils.buildDataInfo(estateRoomService.page(PageUtils.buildPage(), qw));
				List<EstateRoom> list = td.getRows();
				num = list.size();
			}
		} else if (sysUser.getUserType() == 0) {
			return 114146;
		} else {
			QueryWrapper<EstateRoom> qw = new QueryWrapper<>();
			if (sysUser.getEstateId() != null) {
				qw.eq("estate_id", sysUser.getEstateId());
			}
			TableDataInfo<EstateRoom> td = PageUtils.buildDataInfo(estateRoomService.page(PageUtils.buildPage(), qw));
			List<EstateRoom> list = td.getRows();
			num = list.size();
		}
		return num;
	}


	/**
	 * 查询 房屋列表
	 */
	@ApiOperation("查询 房屋列表 ")
	@PreAuthorize("@ss.hasPermi('module:estateRoom:list')")
	@GetMapping("/getTransferData")
	public AjaxResult<Map<String, Object>> getTransferData(@Validated EstateRoom estateRoom) {
		QueryWrapper<EstateRoom> qw = new QueryWrapper<>();
		if (estateRoom.getEstateId() != null) {
			qw.eq("estate_id", estateRoom.getEstateId());
		}
		if (estateRoom.getBuildId() != null) {
			qw.eq("build_id", estateRoom.getBuildId());
		}
		if (estateRoom.getUnitId() != null) {
			qw.eq("unit_id", estateRoom.getUnitId());
		}
		if (estateRoom.getFloorId() != null) {
			qw.eq("floor_id", estateRoom.getFloorId());
		}
		qw.orderByAsc("id");

		Map<String, Object> map = new HashMap<>();
		List<Integer> valueRoomIds = new ArrayList<>();
//		List<EstateRoom> valueRuleList = new ArrayList<>();
		List<EstateRoom> valueRoomList = estateRoomService.list(qw);
		if (CollUtil.isNotEmpty(valueRoomList)) {
			for (EstateRoom room : valueRoomList) {
//				ProductRuleVO ruleVO = new ProductRuleVO();
//				ruleVO.setRuleId(rule.getId());
//				ruleVO.setRuleName(rule.getRuleName());
				valueRoomIds.add(room.getId());
//				valueRuleList.add(ruleVO);
			}
		}
		map.put("valueRoomList", valueRoomList);
		map.put("valueRoomIds", valueRoomIds);

		List<EstateRoom> allRoomList = new ArrayList<>();

		QueryWrapper<EstateRoom> qwAll = new QueryWrapper<>();
		if (estateRoom.getEstateId() != null) {
			qwAll.eq("estate_id", estateRoom.getEstateId());
		}
//		qwAll.eq("floor_id", 0);
//		if(estateRoom.getBuildId() != null){
//			qwAll.eq("build_id", estateRoom.getBuildId());
//		}
//		if(estateRoom.getUnitId() != null){
//			qwAll.eq("unit_id", estateRoom.getUnitId());
//		}
//		if(estateRoom.getFloorId() != null){
//			qwAll.eq("floor_id", estateRoom.getFloorId());
//		}

		qwAll.orderByAsc("id");
		List<EstateRoom> allDataList = estateRoomService.list(qwAll);
		if (CollUtil.isNotEmpty(allDataList)) {
			for (EstateRoom room : allDataList) {
//				ProductRuleVO ruleVO = new ProductRuleVO();
//				ruleVO.setRuleId(rule.getId());
//				ruleVO.setRuleName(rule.getRuleName());
//				allRuleList.add(ruleVO);
			}
		}
		map.put("allRoomList", allDataList);
		return AjaxResult.success(map);
	}


	/**
	 * 导出小区内的房屋列信息列表
	 */
	@ApiOperation("导出小区内的房屋列信息列表")
	@PreAuthorize("@ss.hasPermi('module:estateRoom:export')")
	@Log(title = "小区内的房屋列信息", businessType = BusinessType.EXPORT)
	@GetMapping("/export")
	public AjaxResult<EstateRoom> export(@Validated EstateRoom estateRoom) {
		QueryWrapper<EstateRoom> qw = new QueryWrapper<>();
		if (estateRoom.getEstateId() != null) {
			qw.eq("estate_id", estateRoom.getEstateId());
		}
		List<EstateRoom> list = estateRoomService.list(qw);
		ExcelUtil<EstateRoom> util = new ExcelUtil<EstateRoom>(EstateRoom.class);
		return util.exportExcel(list, "小区内的房屋列信息");
	}

	/**
	 * 导出小区内的水表底数列表
	 */
	@ApiOperation("导出小区内的房屋列信息列表")
	@PreAuthorize("@ss.hasPermi('module:estateRoom:waterExport')")
	@Log(title = "小区内的房屋列信息", businessType = BusinessType.EXPORT)
	@GetMapping("/waterExport")
	public AjaxResult<PropertyWaterTemplateExcel> waterExport(@Validated EstateRoom estateRoom) {
		QueryWrapper<PropertyFeeOrderTemplate> qw = new QueryWrapper<>();
		qw.eq("estate_id", estateRoom.getEstateId());
		qw.eq("fee_type", "water");
//        qw.eq("fee_type","eletrict");
		List<PropertyFeeOrderTemplate> list1 = propertyFeeOrderTemplateService.list(qw);
		List<PropertyWaterTemplateExcel> waterList = new ArrayList<>();
		for (PropertyFeeOrderTemplate list : list1) {
			PropertyWaterTemplateExcel water = new PropertyWaterTemplateExcel();
			water.setFeeType("水费");
			if (list.getState() == 0) {
				water.setStateStr("未交费");
			} else if (list.getState() == 1) {
				water.setStateStr("线上交费");
			} else if (list.getState() == 2) {
				water.setStateStr("线下交费");
			}
			if (list.getRoomNo() != null) {
				water.setRoomNo(list.getRoomNo());
			}
			if (list.getBeginCount() != null) {
				water.setBeginCount(list.getBeginCount());
			}
			if (list.getEndCount() != null) {
				water.setEndCount(list.getEndCount());
			}
			if (list.getYearNum() != null) {
				water.setYearNum(list.getYearNum());
			}
			if (list.getMonthNum() != null) {
				water.setMonthNum(list.getMonthNum());
			}
			if (list.getRealName() != null) {
				water.setUserName(list.getRealName());
			}
			if (list.getTotalPrice() != null) {
				water.setTotalPrice(list.getTotalPrice());
			}
			if (list.getPaidCount() != null) {
				water.setPaidCount(list.getPaidCount());
			}
			waterList.add(water);
		}
		ExcelUtil<PropertyWaterTemplateExcel> util = new ExcelUtil<>(PropertyWaterTemplateExcel.class);
		return util.exportExcel(waterList, "小区内的水表信息");
	}

	/**
	 * 导出小区内的电表底数列表
	 */
	@ApiOperation("导出小区内的房屋列信息列表")
	@PreAuthorize("@ss.hasPermi('module:estateRoom:eletrictExport')")
	@Log(title = "小区内的房屋列信息", businessType = BusinessType.EXPORT)
	@GetMapping("/eletrictExport")
	public AjaxResult<PropertyWaterTemplateExcel> eletrictExport(@Validated EstateRoom estateRoom) {
		QueryWrapper<PropertyFeeOrderTemplate> qw = new QueryWrapper<>();
		qw.eq("estate_id", estateRoom.getEstateId());
		qw.eq("fee_type", "eletrict");
//        qw.eq("fee_type","eletrict");
		List<PropertyFeeOrderTemplate> list1 = propertyFeeOrderTemplateService.list(qw);
		List<PropertyWaterTemplateExcel> waterList = new ArrayList<>();
		for (PropertyFeeOrderTemplate list : list1) {
			PropertyWaterTemplateExcel water = new PropertyWaterTemplateExcel();
			water.setFeeType("电费");
			if (list.getState() == 0) {
				water.setStateStr("未交费");
			} else if (list.getState() == 1) {
				water.setStateStr("线上交费");
			} else if (list.getState() == 2) {
				water.setStateStr("线下交费");
			}
			if (list.getRoomNo() != null) {
				water.setRoomNo(list.getRoomNo());
			}
			if (list.getBeginCount() != null) {
				water.setBeginCount(list.getBeginCount());
			}
			if (list.getEndCount() != null) {
				water.setEndCount(list.getEndCount());
			}
			if (list.getYearNum() != null) {
				water.setYearNum(list.getYearNum());
			}
			if (list.getMonthNum() != null) {
				water.setMonthNum(list.getMonthNum());
			}
			if (list.getRealName() != null) {
				water.setUserName(list.getRealName());
			}
			if (list.getTotalPrice() != null) {
				water.setTotalPrice(list.getTotalPrice());
			}
			if (list.getPaidCount() != null) {
				water.setPaidCount(list.getPaidCount());
			}
			waterList.add(water);
		}
		ExcelUtil<PropertyWaterTemplateExcel> util = new ExcelUtil<>(PropertyWaterTemplateExcel.class);
		return util.exportExcel(waterList, "小区内的电表信息");
	}

	/**
	 * 获取小区内的房屋列信息详细信息
	 */
	@ApiOperation("获取小区内的房屋列信息详细信息")
	@PreAuthorize("@ss.hasPermi('module:estateRoom:query')")
	@GetMapping("/{id}")
	public AjaxResult<EstateRoom> getInfo(@NotNull(message = "主键不能为空") @PathVariable("id") Long id) {
		EstateRoom estateRoom = estateRoomService.getById(id);
		return AjaxResult.success(estateRoom);
	}

	/**
	 * 获取小区内的房屋套内余额信息
	 */
	@ApiOperation("获取小区内的房屋套内余额信息")
	@PreAuthorize("@ss.hasPermi('module:estateRoom:query')")
	@GetMapping("account/{id}")
	public Double getAccount(@NotNull(message = "主键不能为空") @PathVariable("id") Long id) {
		EstateRoom estateRoom = estateRoomService.getById(id);
		if (ObjectUtil.isEmpty(estateRoom.getAccount())) {
			return Double.valueOf(0.00);
		}
		return estateRoom.getAccount();
	}


	/**
	 * 新增小区内的房屋列信息
	 */
	@ApiOperation("新增小区内的房屋列信息")
	@PreAuthorize("@ss.hasPermi('module:estateRoom:add')")
	@Log(title = "小区内的房屋列信息", businessType = BusinessType.INSERT)
	@RepeatSubmit
	@PostMapping()
	public AjaxResult<Void> add(@Validated(AddGroup.class) @RequestBody EstateRoom estateRoom) {
		Estate estate = estateService.findById(estateRoom.getEstateId());

		if (estate != null) {
			estateRoom.setEstateName(estate.getEstateName());
		}
		estateRoom.setAccount(0.00);
		boolean bl = estateRoomService.save(estateRoom);
		if (bl) {
			try {
				estateRoom = estateRoomService.getById(estateRoom.getId());
				String fileName = "room_qr_" + estateRoom.getId() + ".jpg";
				String content = "https://www.caihengyun.com/wxmini/room/info?id=" + estateRoom.getId();
				int upload_type = FileUploadUtils.TYPE_ESTATE_ROOM_PHOTOS;
				System.out.println("content:  " + content);
				String img_key = FileUploadUtils.getUploadPrefix(upload_type) + fileName;

				QRCodeUtilEx.createQrCodeImg(content, estateRoom.getEstateName() + " " + estateRoom.getRoomNo(), null, uploadPath + "/" + img_key, true, fileName, upload_type);
				estateRoom.setQrCode(img_key);
			} catch (Exception ex) {
				ex.printStackTrace();
			}
		}

		return toAjax(bl ? 1 : 0);
	}

	/**
	 * 修改小区内的房屋列信息
	 */
	@ApiOperation("修改小区内的房屋列信息")
	@PreAuthorize("@ss.hasPermi('module:estateRoom:edit')")
	@Log(title = "小区内的房屋列信息", businessType = BusinessType.UPDATE)
	@RepeatSubmit
	@PutMapping()
	public AjaxResult<Void> edit(@Validated(EditGroup.class) @RequestBody EstateRoom estateRoom) {
		int ret = estateRoomService.updateRoom(estateRoom);
		return toAjax(ret);
	}

	/**
	 * 给欠费的房间发送短信
	 */
	@ApiOperation("修改小区内的房屋列信息")
	@PreAuthorize("@ss.hasPermi('module:estateRoom:edit')")
	@Log(title = "小区内的房屋列信息", businessType = BusinessType.UPDATE)
	@RepeatSubmit
	@PostMapping("/sendSmsToUnPay")
	public AjaxResult<Void> sendSmsToUnPay(@Validated(EditGroup.class) @RequestBody EstateRoom estateRoom) {
		int ret = estateRoomService.sendSmsByPropertyFeeToRoomUser(estateRoom);
		return toAjax(ret);
	}


	/**
	 * 修改小区内的房屋列信息
	 */
	@ApiOperation("修改小区内的房屋列信息")
	@PreAuthorize("@ss.hasPermi('module:estateRoom:edit')")
	@Log(title = "小区内的房屋列信息", businessType = BusinessType.UPDATE)
	@RepeatSubmit
	@PutMapping("/editFloor")
	public AjaxResult<Void> editFloor(@Validated(EditGroup.class) @RequestBody EstateRoom estateRoom) {
		EstateRoom estateRoom1 = estateRoomService.findById(estateRoom.getId());
		if (estateRoom1 != null) {
			if (estateRoom.getBuildId() != null) {
				estateRoom1.setBuildId(estateRoom.getBuildId());
			}

			if (estateRoom.getUnitId() != null) {
				estateRoom1.setUnitId(estateRoom.getUnitId());
				EstateBuildUnit unit = estateBuildUnitService.findById(estateRoom.getUnitId());
				if (unit != null) {
					estateRoom1.setUnitNo(estateRoom.getUnitNo());
				}
			}
			if (estateRoom.getFloorId() != null) {
				estateRoom1.setFloorId(estateRoom.getFloorId());
			}
			boolean ret = estateRoomService.updateById(estateRoom1);
			return toAjax(ret);
		}

		return toAjax(0);
	}

	/**
	 * 套内账号充值
	 */
	@ApiOperation("套内账号充值")
	@PreAuthorize("@ss.hasPermi('module:estateRoom:edit')")
	@Log(title = "小区内的房屋列信息", businessType = BusinessType.UPDATE)
	@RepeatSubmit
	@PutMapping("/chongzhi")
	public AjaxResult<Void> chongzhi(@Validated(EditGroup.class) @RequestBody EstateRoom estateRoom) {
		SysUser sysUser = getUser();
		EstateRoom room = estateRoomService.findById(estateRoom.getId());
		room.setAccount(room.getAccount() + estateRoom.getChongzhi());
		estateRoomService.updateById(room);
		Estate estate = estateService.findById(room.getEstateId());

		//创建套内账户充值记录
		EstateRoomAccountRecord record = new EstateRoomAccountRecord();
		record.setPropertyId(estate.getPropertyId());
		record.setEstateId(room.getEstateId());
		record.setSysUserId(sysUser.getUserId());
		record.setAccount(room.getAccount());
		record.setRechargeWay(estateRoom.getRechargeWay());
		if (estateRoom.getChongzhi() > 0) {
			record.setRechargeOrUse(0L);
		} else {
			record.setRechargeOrUse(1L);
		}
		record.setUsageAmount(estateRoom.getChongzhi());
		record.setRoomNo(room.getRoomNo());
		record.setRoomId(estateRoom.getId());
		boolean b = estateRoomAccountRecordService.save(record);

		//创建propertyOrder记录
		if (b) {
			PropertyFeeOrder order = new PropertyFeeOrder();
			Date date = new Date();
			Property property = propertyService.findById(estate.getPropertyId());
			if (property != null) {
				order.setPropertyName(property.getPropertyName());
			}
			order.setAccountOrderId(record.getId());
			order.setEstateId(room.getEstateId());
			order.setPropertyId(estate.getPropertyId());
			order.setAccountFee(estateRoom.getChongzhi());
			order.setEstateName(estate.getEstateName());
			order.setRoomId(room.getId());
			order.setPlatform("web");
			if (estateRoom.getRechargeWay() == 1) {
				order.setPayPlatform(2);
			} else if (estateRoom.getRechargeWay() == 2) {
				order.setPayPlatform(3);
			} else if (estateRoom.getRechargeWay() == 3) {
				order.setPayPlatform(4);
			} else if (estateRoom.getRechargeWay() == 4) {
				order.setPayPlatform(5);
			} else if (estateRoom.getRechargeWay() == 10) {
				order.setPayPlatform(10);
			}
			order.setUserId(0);
			order.setNickName(sysUser.getNickName());
			order.setRealName(room.getRealName());
			order.setRoomNo(room.getRoomNo());
			order.setPhoneNum(room.getPhoneNum());
			order.setRoomAreas(Double.valueOf(room.getRoomArea()));
			order.setRoomType(room.getRoomType());
			order.setTotalMoney(BigDecimal.valueOf(estateRoom.getChongzhi()));
			order.setPayMoney(BigDecimal.valueOf(estateRoom.getChongzhi()));
			order.setWyfFee(BigDecimal.valueOf(0.00));
			order.setState(4);
			order.setPayTime(date);
			order.setDkRate(Double.valueOf(0));
			order.setHandleSysUserId(sysUser.getUserId());
			order.setHandleUserName(sysUser.getNickName());
			order.setHandleTime(date);
			order.setRemark(estateRoom.getRemake());
			b = propertyFeeOrderService.save(order);
			//创建propertyOrderInfo记录
			if (b) {
				PropertyFeeOrderInfo info = new PropertyFeeOrderInfo();
				info.setOrderId(order.getId());
				info.setUserId(0);
				info.setEstateId(order.getEstateId());
				info.setRoomId(order.getRoomId());
				info.setFeeType("account");
				info.setTotalPrice(BigDecimal.valueOf(estateRoom.getChongzhi()));
				info.setPayPrice(info.getTotalPrice());
				info.setState(1);
				info.setPayTime(date);
				b = propertyFeeOrderInfoService.save(info);
			}
		}
		return toAjax(b);
	}

	/**
	 * 修改小区内的房屋列信息(不需要审批的)
	 */
//	@ApiOperation("修改小区内的房屋空置房")
//	@PreAuthorize("@ss.hasPermi('module:estateRoom:edit')")
//	@Log(title = "小区内的房屋列信息", businessType = BusinessType.UPDATE)
//	@RepeatSubmit
//	@PutMapping("/updateVacant")
//	public AjaxResult<Void> updateVacant(@Validated(EditGroup.class) @RequestBody EstateRoom estateRoom) {
//		EstateRoom estateRoom1 = estateRoomService.findById(estateRoom.getId());
//		if(estateRoom1 != null){
//			estateRoom1.setVacantBeginDate(estateRoom.getVacantBeginDate());
//			estateRoom1.setVacantEndDate(estateRoom.getVacantEndDate());
//			boolean ret = estateRoomService.updateById(estateRoom1);
//			//设置空置时间段的缴费金额
//			if (ret){
//				int kuanNian = 0;
//				//物业费处理 -优惠金额设置为需缴费金额的0.4倍
//				QueryWrapper<PropertyFeeOrderTemplate> qwWyf = new QueryWrapper<>();
//				qwWyf.eq("room_id",estateRoom.getId());
//				qwWyf.eq("fee_type","wyf");
//				qwWyf.eq("state",0);
//				//筛选时间
//				//开始时间
//				Calendar date = Calendar.getInstance();
//				date.setTime(estateRoom.getVacantBeginDate());
//				int yearBeginNum = date.get(Calendar.YEAR);
//				int monthBeginNum = date.get(Calendar.MONTH)+1;
//				//结束时间
//				date.setTime(estateRoom.getVacantEndDate());
//				int yearEndNum = date.get(Calendar.YEAR);
//				int monthEndNum = date.get(Calendar.MONTH)+1;
//				//判断是否跨年
//				if (yearBeginNum==yearEndNum){
//					qwWyf.between("year_num",yearBeginNum,yearEndNum);
//					qwWyf.between("month_num",monthBeginNum,monthEndNum);
//				}else {
//					qwWyf.between("year_num",yearBeginNum,yearBeginNum);
//					qwWyf.between("month_num",monthBeginNum,12);
//					kuanNian = yearEndNum-yearBeginNum;
//				}
//				List<PropertyFeeOrderTemplate> templateList = propertyFeeOrderTemplateService.list(qwWyf);
//				//如果出现跨年的处理
//				if (kuanNian!=0){
//					//跨一年 -查询并把第二年的数据并入templateList
//					if (kuanNian==1){
//						QueryWrapper qwKua = new QueryWrapper<>();
//						qwKua.eq("room_id",estateRoom.getId());
//						qwKua.eq("fee_type","wyf");
//						qwKua.eq("state",0);
//						qwKua.between("year_num",yearEndNum,yearEndNum);
//						qwKua.between("month_num",1,monthEndNum);
//						List<PropertyFeeOrderTemplate> list = propertyFeeOrderTemplateService.list(qwKua);
//						for (PropertyFeeOrderTemplate list1:list){
//							templateList.add(list1);
//						}
//					}
//					//跨一年以上 -查询中间几年的数据和最后一年的数据 并入templateList
//					if (kuanNian>1){
//						for (int i=1;i<kuanNian;i++){
//							QueryWrapper qwKua = new QueryWrapper<>();
//							qwKua.eq("room_id",estateRoom.getId());
//							qwKua.eq("fee_type","wyf");
//							qwKua.eq("state",0);
//							qwKua.between("year_num",yearBeginNum+i,yearBeginNum+i);
//							qwKua.between("month_num",1,12);
//							List<PropertyFeeOrderTemplate> list = propertyFeeOrderTemplateService.list(qwKua);
//							for (PropertyFeeOrderTemplate list1:list){
//								templateList.add(list1);
//							}
//						}
//						QueryWrapper qwKua1 = new QueryWrapper<>();
//						qwKua1.eq("room_id",estateRoom.getId());
//						qwKua1.eq("fee_type","wyf");
//						qwKua1.eq("state",0);
//						qwKua1.between("year_num",yearEndNum,yearEndNum);
//						qwKua1.between("month_num",1,monthEndNum);
//						List<PropertyFeeOrderTemplate> list = propertyFeeOrderTemplateService.list(qwKua1);
//						for (PropertyFeeOrderTemplate list1:list){
//							templateList.add(list1);
//						}
//					}
//				}
//				for (PropertyFeeOrderTemplate template : templateList){
//					if (estateRoom.getCount()==null){
//						Double youhui = template.getTotalPrice().doubleValue()*0.4;
//						BigDecimal youhuiMoney = BigDecimal.valueOf(youhui);
//						template.setYouhuiPrice(youhuiMoney);
//						ret = propertyFeeOrderTemplateService.updateById(template);
//					}else {
//						Double zhekou = 10 - estateRoom.getCount();
//						Double youhui = template.getTotalPrice().doubleValue()*zhekou/10;
//						BigDecimal youhuiMoney = BigDecimal.valueOf(youhui);
//						template.setYouhuiPrice(youhuiMoney);
//						ret = propertyFeeOrderTemplateService.updateById(template);
//					}
//
//				}
//				//垃圾处理费处理 -优惠金额设置为需缴费金额
//				QueryWrapper<PropertyFeeOrderTemplate> qwRubbish = new QueryWrapper<>();
//				qwRubbish.eq("room_id",estateRoom.getId());
//				qwRubbish.eq("fee_type","rubbish");
//				qwRubbish.eq("state",0);
//				//筛选时间
//				//开始时间
//				date.setTime(estateRoom.getVacantBeginDate());
//				yearBeginNum = date.get(Calendar.YEAR);
//				monthBeginNum = date.get(Calendar.MONTH)+1;
//				//结束时间
//				date.setTime(estateRoom.getVacantEndDate());
//				yearEndNum = date.get(Calendar.YEAR);
//				monthEndNum = date.get(Calendar.MONTH)+1;
//				//判断是否跨年
//				if (yearBeginNum==yearEndNum){
//					qwRubbish.between("year_num",yearBeginNum,yearEndNum);
//					qwRubbish.between("month_num",monthBeginNum,monthEndNum);
//				}else {
//					qwRubbish.between("year_num",yearBeginNum,yearBeginNum);
//					qwRubbish.between("month_num",monthBeginNum,12);
//					kuanNian = yearEndNum-yearBeginNum;
//				}
//				List<PropertyFeeOrderTemplate> rubbishList = propertyFeeOrderTemplateService.list(qwRubbish);
//				if (kuanNian!=0){
//					//跨一年 -查询并把第二年的数据并入templateList
//					if (kuanNian==1){
//						QueryWrapper qwKua = new QueryWrapper<>();
//						qwKua.eq("room_id",estateRoom.getId());
//						qwKua.eq("fee_type","rubbish");
//						qwKua.eq("state",0);
//						qwKua.between("year_num",yearEndNum,yearEndNum);
//						qwKua.between("month_num",1,monthEndNum);
//						List<PropertyFeeOrderTemplate> list = propertyFeeOrderTemplateService.list(qwKua);
//						for (PropertyFeeOrderTemplate list1:list){
//							rubbishList.add(list1);
//						}
//					}
//					//跨一年以上 -查询中间几年的数据和最后一年的数据 并入templateList
//					if (kuanNian>1){
//						for (int i=1;i<kuanNian;i++){
//							QueryWrapper qwKua = new QueryWrapper<>();
//							qwKua.eq("room_id",estateRoom.getId());
//							qwKua.eq("fee_type","rubbish");
//							qwKua.eq("state",0);
//							qwKua.between("year_num",yearBeginNum+i,yearBeginNum+i);
//							qwKua.between("month_num",1,12);
//							List<PropertyFeeOrderTemplate> list = propertyFeeOrderTemplateService.list(qwKua);
//							for (PropertyFeeOrderTemplate list1:list){
//								rubbishList.add(list1);
//							}
//						}
//						QueryWrapper qwKua1 = new QueryWrapper<>();
//						qwKua1.eq("room_id",estateRoom.getId());
//						qwKua1.eq("fee_type","rubbish");
//						qwKua1.eq("state",0);
//						qwKua1.between("year_num",yearEndNum,yearEndNum);
//						qwKua1.between("month_num",1,monthEndNum);
//						List<PropertyFeeOrderTemplate> list = propertyFeeOrderTemplateService.list(qwKua1);
//						for (PropertyFeeOrderTemplate list1:list){
//							rubbishList.add(list1);
//						}
//					}
//				}
//				for (PropertyFeeOrderTemplate template : rubbishList){
//					if (estateRoom.getCount()==null){
//						template.setYouhuiPrice(template.getTotalPrice());
//						ret = propertyFeeOrderTemplateService.updateById(template);
//					}
//				}
//			}
//			return toAjax(ret);
//		}
//		return toAjax(0);
//	}


	/**
	 * 修改小区内的房屋列信息(需要审批的)
	 */
	@ApiOperation("修改小区内的房屋空置房")
	@PreAuthorize("@ss.hasPermi('module:estateRoom:edit')")
	@Log(title = "小区内的房屋列信息", businessType = BusinessType.UPDATE)
	@RepeatSubmit
	@PutMapping("/updateVacant")
	public AjaxResult<Void> updateVacant(@Validated(EditGroup.class) @RequestBody EstateRoom estateRoom) {
		EstateRoom estateRoom1 = estateRoomService.findById(estateRoom.getId());
		if (estateRoom1 != null) {
			estateRoom1.setVacantBeginDate(estateRoom.getVacantBeginDate());
			estateRoom1.setVacantEndDate(estateRoom.getVacantEndDate());
			boolean ret = estateRoomService.updateById(estateRoom1);
			//设置空置时间段的缴费金额
			if (ret) {
				int kuanNian = 0;
				//物业费处理 -优惠金额设置为需缴费金额的0.4倍
				QueryWrapper<PropertyFeeOrderTemplate> qwWyf = new QueryWrapper<>();
				qwWyf.eq("room_id", estateRoom.getId());
				qwWyf.eq("fee_type", "wyf");
				qwWyf.eq("state", 0);
				//筛选时间
				//开始时间
				Calendar date = Calendar.getInstance();
				date.setTime(estateRoom.getVacantBeginDate());
				int yearBeginNum = date.get(Calendar.YEAR);
				int monthBeginNum = date.get(Calendar.MONTH) + 1;
				//结束时间
				date.setTime(estateRoom.getVacantEndDate());
				int yearEndNum = date.get(Calendar.YEAR);
				int monthEndNum = date.get(Calendar.MONTH) + 1;
				//判断是否跨年
				if (yearBeginNum == yearEndNum) {
					qwWyf.between("year_num", yearBeginNum, yearEndNum);
					qwWyf.between("month_num", monthBeginNum, monthEndNum);
				} else {
					qwWyf.between("year_num", yearBeginNum, yearBeginNum);
					qwWyf.between("month_num", monthBeginNum, 12);
					kuanNian = yearEndNum - yearBeginNum;
				}
				List<PropertyFeeOrderTemplate> templateList = propertyFeeOrderTemplateService.list(qwWyf);
				//如果出现跨年的处理
				if (kuanNian != 0) {
					//跨一年 -查询并把第二年的数据并入templateList
					if (kuanNian == 1) {
						QueryWrapper qwKua = new QueryWrapper<>();
						qwKua.eq("room_id", estateRoom.getId());
						qwKua.eq("fee_type", "wyf");
						qwKua.eq("state", 0);
						qwKua.between("year_num", yearEndNum, yearEndNum);
						qwKua.between("month_num", 1, monthEndNum);
						List<PropertyFeeOrderTemplate> list = propertyFeeOrderTemplateService.list(qwKua);
						for (PropertyFeeOrderTemplate list1 : list) {
							templateList.add(list1);
						}
					}
					//跨一年以上 -查询中间几年的数据和最后一年的数据 并入templateList
					if (kuanNian > 1) {
						for (int i = 1; i < kuanNian; i++) {
							QueryWrapper qwKua = new QueryWrapper<>();
							qwKua.eq("room_id", estateRoom.getId());
							qwKua.eq("fee_type", "wyf");
							qwKua.eq("state", 0);
							qwKua.between("year_num", yearBeginNum + i, yearBeginNum + i);
							qwKua.between("month_num", 1, 12);
							List<PropertyFeeOrderTemplate> list = propertyFeeOrderTemplateService.list(qwKua);
							for (PropertyFeeOrderTemplate list1 : list) {
								templateList.add(list1);
							}
						}
						QueryWrapper qwKua1 = new QueryWrapper<>();
						qwKua1.eq("room_id", estateRoom.getId());
						qwKua1.eq("fee_type", "wyf");
						qwKua1.eq("state", 0);
						qwKua1.between("year_num", yearEndNum, yearEndNum);
						qwKua1.between("month_num", 1, monthEndNum);
						List<PropertyFeeOrderTemplate> list = propertyFeeOrderTemplateService.list(qwKua1);
						for (PropertyFeeOrderTemplate list1 : list) {
							templateList.add(list1);
						}
					}
				}
				//创建审批条目
				SysUser user = getUser();
				PropertyFeeOrderTemplateApprover approver = new PropertyFeeOrderTemplateApprover();
				approver.setEstateId(Long.valueOf(estateRoom.getEstateId()));
				approver.setApplicantId(user.getUserId());
				approver.setApplicantName(user.getNickName());
				approver.setEstateName(estateService.findById(estateRoom.getEstateId()).getEstateName());
				approver.setInOrOut(1L);
				approver.setState(0L);

				//判断每月缴费金额是否相同或有已交费的月份  如果不同不能生成审核订单
				BigDecimal jiaofei = templateList.get(0).getTotalPrice();
				for (PropertyFeeOrderTemplate template : templateList) {
					if (!jiaofei.equals(template.getTotalPrice())){
						return toAjax(0);
					}
					if (template.getState()!=0){
						return toAjax(0);
					}
				}
				approver.setApplicantMonth(Long.valueOf(templateList.size()));
				if (estateRoom.getCount() == null) {
					BigDecimal decimal = new BigDecimal(String.valueOf(templateList.get(0).getTotalPrice().doubleValue() * 0.4));
					BigDecimal result = decimal.setScale(2, RoundingMode.HALF_UP);
					approver.setTotalPrice(result);
					approver.setRemark(estateRoom.getRoomNo() + "空置房物业费申请");

					//垃圾处理费处理 -优惠金额设置为需缴费金额
					QueryWrapper<PropertyFeeOrderTemplate> qwRubbish = new QueryWrapper<>();
					qwRubbish.eq("room_id", estateRoom.getId());
					qwRubbish.eq("fee_type", "rubbish");
					qwRubbish.eq("state", 0);
					//筛选时间
					//开始时间
					date.setTime(estateRoom.getVacantBeginDate());
					yearBeginNum = date.get(Calendar.YEAR);
					monthBeginNum = date.get(Calendar.MONTH) + 1;
					//结束时间
					date.setTime(estateRoom.getVacantEndDate());
					yearEndNum = date.get(Calendar.YEAR);
					monthEndNum = date.get(Calendar.MONTH) + 1;
					//判断是否跨年
					if (yearBeginNum == yearEndNum) {
						qwRubbish.between("year_num", yearBeginNum, yearEndNum);
						qwRubbish.between("month_num", monthBeginNum, monthEndNum);
					} else {
						qwRubbish.between("year_num", yearBeginNum, yearBeginNum);
						qwRubbish.between("month_num", monthBeginNum, 12);
						kuanNian = yearEndNum - yearBeginNum;
					}
					List<PropertyFeeOrderTemplate> rubbishList = propertyFeeOrderTemplateService.list(qwRubbish);
					if (rubbishList.size()>0){
						if (kuanNian != 0) {
							//跨一年 -查询并把第二年的数据并入templateList
							if (kuanNian == 1) {
								QueryWrapper qwKua = new QueryWrapper<>();
								qwKua.eq("room_id", estateRoom.getId());
								qwKua.eq("fee_type", "rubbish");
								qwKua.eq("state", 0);
								qwKua.between("year_num", yearEndNum, yearEndNum);
								qwKua.between("month_num", 1, monthEndNum);
								List<PropertyFeeOrderTemplate> list = propertyFeeOrderTemplateService.list(qwKua);
								for (PropertyFeeOrderTemplate list1 : list) {
									rubbishList.add(list1);
								}
							}
							//跨一年以上 -查询中间几年的数据和最后一年的数据 并入templateList
							if (kuanNian > 1) {
								for (int i = 1; i < kuanNian; i++) {
									QueryWrapper qwKua = new QueryWrapper<>();
									qwKua.eq("room_id", estateRoom.getId());
									qwKua.eq("fee_type", "rubbish");
									qwKua.eq("state", 0);
									qwKua.between("year_num", yearBeginNum + i, yearBeginNum + i);
									qwKua.between("month_num", 1, 12);
									List<PropertyFeeOrderTemplate> list = propertyFeeOrderTemplateService.list(qwKua);
									for (PropertyFeeOrderTemplate list1 : list) {
										rubbishList.add(list1);
									}
								}
								QueryWrapper qwKua1 = new QueryWrapper<>();
								qwKua1.eq("room_id", estateRoom.getId());
								qwKua1.eq("fee_type", "rubbish");
								qwKua1.eq("state", 0);
								qwKua1.between("year_num", yearEndNum, yearEndNum);
								qwKua1.between("month_num", 1, monthEndNum);
								List<PropertyFeeOrderTemplate> list = propertyFeeOrderTemplateService.list(qwKua1);
								for (PropertyFeeOrderTemplate list1 : list) {
									rubbishList.add(list1);
								}
							}
						}
						//创建审批条目
						PropertyFeeOrderTemplateApprover approverRubbish = new PropertyFeeOrderTemplateApprover();
						approverRubbish.setEstateId(Long.valueOf(estateRoom.getEstateId()));
						approverRubbish.setApplicantId(user.getUserId());
						approverRubbish.setApplicantName(user.getNickName());
						approverRubbish.setEstateName(estateRoom.getEstateName());
						approverRubbish.setInOrOut(1L);
						approverRubbish.setState(0L);
						approverRubbish.setApplicantMonth(Long.valueOf(rubbishList.size()));
						if (estateRoom.getCount() == null) {
							decimal = new BigDecimal(String.valueOf(rubbishList.get(0).getTotalPrice().doubleValue()));
							result = decimal.setScale(2, RoundingMode.HALF_UP);
							approverRubbish.setTotalPrice(result);
							approverRubbish.setRemark(estateRoom.getRoomNo() + "空置房垃圾费申请");
						}
						ret = propertyFeeOrderTemplateApproverService.save(approverRubbish);
						//创建审核详情
						for (PropertyFeeOrderTemplate template : rubbishList) {
							PropertyFeeOrderTemplateApproverInfo info = new PropertyFeeOrderTemplateApproverInfo();
							info.setApproverId(approverRubbish.getId());
							info.setTemplateId(template.getId());
							ret = propertyFeeOrderTemplateApproverInfoService.save(info);
						}
					}


				} else {
					Double zhekou = 10 - estateRoom.getCount();
					approver.setTotalPrice(BigDecimal.valueOf(templateList.get(0).getTotalPrice().doubleValue() * zhekou / 10));
					approver.setRemark(estateRoomService.findById(estateRoom.getId()).getRoomNo() + "物业费"+estateRoom.getCount()+"折申请");
				}
				ret = propertyFeeOrderTemplateApproverService.save(approver);
				//创建审核详情
				for (PropertyFeeOrderTemplate template : templateList) {
					PropertyFeeOrderTemplateApproverInfo info = new PropertyFeeOrderTemplateApproverInfo();
					info.setApproverId(approver.getId());
					info.setTemplateId(template.getId());
					ret = propertyFeeOrderTemplateApproverInfoService.save(info);
				}

			}
			return toAjax(ret);
		}
		return toAjax(0);
	}

	/**
	 * 取消小区内的房屋列信息
	 */
	@ApiOperation("取消小区内的房屋空置房")
	@PreAuthorize("@ss.hasPermi('module:estateRoom:edit')")
	@Log(title = "小区内的房屋列信息", businessType = BusinessType.UPDATE)
	@RepeatSubmit
	@PutMapping("/delectVacant")
	public AjaxResult<Void> delectVacant(@Validated(EditGroup.class) @RequestBody EstateRoom estateRoom) {
		EstateRoom estateRoom1 = estateRoomService.findById(estateRoom.getId());
		if (estateRoom1 != null) {
			estateRoom1.setVacantBeginDate(estateRoom.getVacantBeginDate());
			estateRoom1.setVacantEndDate(estateRoom.getVacantEndDate());
			boolean ret = estateRoomService.updateById(estateRoom1);
			//设置空置时间段的缴费金额
			if (ret) {
				int kuanNian = 0;
				//物业费处理 -优惠金额设置为需缴费金额的0.4倍
				QueryWrapper<PropertyFeeOrderTemplate> qwWyf = new QueryWrapper<>();
				qwWyf.eq("room_id", estateRoom.getId());
				qwWyf.eq("fee_type", "wyf");
				qwWyf.eq("state", 0);
				//筛选时间
				//开始时间
				Calendar date = Calendar.getInstance();
				date.setTime(estateRoom.getVacantBeginDate());
				int yearBeginNum = date.get(Calendar.YEAR);
				int monthBeginNum = date.get(Calendar.MONTH) + 1;
				//结束时间
				date.setTime(estateRoom.getVacantEndDate());
				int yearEndNum = date.get(Calendar.YEAR);
				int monthEndNum = date.get(Calendar.MONTH) + 1;
				//判断是否跨年
				if (yearBeginNum == yearEndNum) {
					qwWyf.between("year_num", yearBeginNum, yearEndNum);
					qwWyf.between("month_num", monthBeginNum, monthEndNum);
				} else {
					qwWyf.between("year_num", yearBeginNum, yearBeginNum);
					qwWyf.between("month_num", monthBeginNum, 12);
					kuanNian = yearEndNum - yearBeginNum;
				}
				List<PropertyFeeOrderTemplate> templateList = propertyFeeOrderTemplateService.list(qwWyf);
				//如果出现跨年的处理
				if (kuanNian != 0) {
					//跨一年 -查询并把第二年的数据并入templateList
					if (kuanNian == 1) {
						QueryWrapper qwKua = new QueryWrapper<>();
						qwKua.eq("room_id", estateRoom.getId());
						qwKua.eq("fee_type", "wyf");
						qwKua.eq("state", 0);
						qwKua.between("year_num", yearEndNum, yearEndNum);
						qwKua.between("month_num", 1, monthEndNum);
						List<PropertyFeeOrderTemplate> list = propertyFeeOrderTemplateService.list(qwKua);
						for (PropertyFeeOrderTemplate list1 : list) {
							templateList.add(list1);
						}
					}
					//跨一年以上 -查询中间几年的数据和最后一年的数据 并入templateList
					if (kuanNian > 1) {
						for (int i = 1; i < kuanNian; i++) {
							QueryWrapper qwKua = new QueryWrapper<>();
							qwKua.eq("room_id", estateRoom.getId());
							qwKua.eq("fee_type", "wyf");
							qwKua.eq("state", 0);
							qwKua.between("year_num", yearBeginNum + i, yearBeginNum + i);
							qwKua.between("month_num", 1, 12);
							List<PropertyFeeOrderTemplate> list = propertyFeeOrderTemplateService.list(qwKua);
							for (PropertyFeeOrderTemplate list1 : list) {
								templateList.add(list1);
							}
						}
						QueryWrapper qwKua1 = new QueryWrapper<>();
						qwKua1.eq("room_id", estateRoom.getId());
						qwKua1.eq("fee_type", "wyf");
						qwKua1.eq("state", 0);
						qwKua1.between("year_num", yearEndNum, yearEndNum);
						qwKua1.between("month_num", 1, monthEndNum);
						List<PropertyFeeOrderTemplate> list = propertyFeeOrderTemplateService.list(qwKua1);
						for (PropertyFeeOrderTemplate list1 : list) {
							templateList.add(list1);
						}
					}
				}

				//创建审批条目
				SysUser user = getUser();
				PropertyFeeOrderTemplateApprover approver = new PropertyFeeOrderTemplateApprover();
				approver.setEstateId(Long.valueOf(estateRoom.getEstateId()));
				approver.setApplicantId(user.getUserId());
				approver.setApplicantName(user.getNickName());
				approver.setEstateName(estateRoom.getEstateName());
				approver.setInOrOut(0L);
				approver.setState(0L);

				//判断每月缴费金额是否相同或有已交费的月份  如果不同不能生成审核订单
				BigDecimal jiaofei = templateList.get(0).getTotalPrice();
				for (PropertyFeeOrderTemplate template : templateList) {
					if (!jiaofei.equals(template.getTotalPrice())){
						return toAjax(0);
					}
					if (template.getState()!=0){
						return toAjax(0);
					}
				}
				approver.setApplicantMonth(Long.valueOf(templateList.size()));
				if (estateRoom.getCount() == null) {
					BigDecimal decimal = new BigDecimal(String.valueOf(0.00));
					BigDecimal result = decimal.setScale(2, RoundingMode.HALF_UP);
					approver.setTotalPrice(result);
					approver.setRemark(estateRoom.getRoomNo() + "空置房物业费撤销申请");
				} else {
					Double zhekou = 10 - estateRoom.getCount();
					approver.setTotalPrice(BigDecimal.valueOf(0.00));
					approver.setRemark(estateRoom.getRoomNo() + "物业费折扣撤销申请");
				}
				ret = propertyFeeOrderTemplateApproverService.save(approver);
				//创建审核详情
				for (PropertyFeeOrderTemplate template : templateList) {

					PropertyFeeOrderTemplateApproverInfo info = new PropertyFeeOrderTemplateApproverInfo();
					info.setApproverId(approver.getId());
					info.setTemplateId(template.getId());
					ret = propertyFeeOrderTemplateApproverInfoService.save(info);
				}
//
//				for (PropertyFeeOrderTemplate template : templateList) {
//					if (estateRoom.getCount() == null) {
//						Double youhui = 0.00;
//						BigDecimal youhuiMoney = BigDecimal.valueOf(youhui);
//						template.setYouhuiPrice(youhuiMoney);
//						ret = propertyFeeOrderTemplateService.updateById(template);
//					} else {
//						Double zhekou = 10.00;
//						Double youhui = template.getTotalPrice().doubleValue() * zhekou / 10;
//						BigDecimal youhuiMoney = BigDecimal.valueOf(youhui);
//						template.setYouhuiPrice(youhuiMoney);
//						ret = propertyFeeOrderTemplateService.updateById(template);
//					}
//
//				}
				//垃圾处理费处理 -优惠金额设置为需缴费金额
				QueryWrapper<PropertyFeeOrderTemplate> qwRubbish = new QueryWrapper<>();
				qwRubbish.eq("room_id", estateRoom.getId());
				qwRubbish.eq("fee_type", "rubbish");
				qwRubbish.eq("state", 0);
				//筛选时间
				//开始时间
				date.setTime(estateRoom.getVacantBeginDate());
				yearBeginNum = date.get(Calendar.YEAR);
				monthBeginNum = date.get(Calendar.MONTH) + 1;
				//结束时间
				date.setTime(estateRoom.getVacantEndDate());
				yearEndNum = date.get(Calendar.YEAR);
				monthEndNum = date.get(Calendar.MONTH) + 1;
				//判断是否跨年
				if (yearBeginNum == yearEndNum) {
					qwRubbish.between("year_num", yearBeginNum, yearEndNum);
					qwRubbish.between("month_num", monthBeginNum, monthEndNum);
				} else {
					qwRubbish.between("year_num", yearBeginNum, yearBeginNum);
					qwRubbish.between("month_num", monthBeginNum, 12);
					kuanNian = yearEndNum - yearBeginNum;
				}
				List<PropertyFeeOrderTemplate> rubbishList = propertyFeeOrderTemplateService.list(qwRubbish);
				if (kuanNian != 0) {
					//跨一年 -查询并把第二年的数据并入templateList
					if (kuanNian == 1) {
						QueryWrapper qwKua = new QueryWrapper<>();
						qwKua.eq("room_id", estateRoom.getId());
						qwKua.eq("fee_type", "rubbish");
						qwKua.eq("state", 0);
						qwKua.between("year_num", yearEndNum, yearEndNum);
						qwKua.between("month_num", 1, monthEndNum);
						List<PropertyFeeOrderTemplate> list = propertyFeeOrderTemplateService.list(qwKua);
						for (PropertyFeeOrderTemplate list1 : list) {
							rubbishList.add(list1);
						}
					}
					//跨一年以上 -查询中间几年的数据和最后一年的数据 并入templateList
					if (kuanNian > 1) {
						for (int i = 1; i < kuanNian; i++) {
							QueryWrapper qwKua = new QueryWrapper<>();
							qwKua.eq("room_id", estateRoom.getId());
							qwKua.eq("fee_type", "rubbish");
							qwKua.eq("state", 0);
							qwKua.between("year_num", yearBeginNum + i, yearBeginNum + i);
							qwKua.between("month_num", 1, 12);
							List<PropertyFeeOrderTemplate> list = propertyFeeOrderTemplateService.list(qwKua);
							for (PropertyFeeOrderTemplate list1 : list) {
								rubbishList.add(list1);
							}
						}
						QueryWrapper qwKua1 = new QueryWrapper<>();
						qwKua1.eq("room_id", estateRoom.getId());
						qwKua1.eq("fee_type", "rubbish");
						qwKua1.eq("state", 0);
						qwKua1.between("year_num", yearEndNum, yearEndNum);
						qwKua1.between("month_num", 1, monthEndNum);
						List<PropertyFeeOrderTemplate> list = propertyFeeOrderTemplateService.list(qwKua1);
						for (PropertyFeeOrderTemplate list1 : list) {
							rubbishList.add(list1);
						}
					}
				}

				//创建审批条目
				PropertyFeeOrderTemplateApprover approverRubbish = new PropertyFeeOrderTemplateApprover();
				approverRubbish.setEstateId(Long.valueOf(estateRoom.getEstateId()));
				approverRubbish.setApplicantId(user.getUserId());
				approverRubbish.setApplicantName(user.getNickName());
				approverRubbish.setEstateName(estateRoom.getEstateName());
				approverRubbish.setInOrOut(0L);
				approverRubbish.setState(0L);
				approverRubbish.setApplicantMonth(Long.valueOf(rubbishList.size()));
				if (estateRoom.getCount() == null) {
					BigDecimal decimal = new BigDecimal(String.valueOf(0.00));
					BigDecimal result = decimal.setScale(2, RoundingMode.HALF_UP);
					approverRubbish.setTotalPrice(result);
					approverRubbish.setRemark(estateRoom.getRoomNo() + "空置房垃圾费撤销申请");
				}
				ret = propertyFeeOrderTemplateApproverService.save(approverRubbish);
				//创建审核详情
				for (PropertyFeeOrderTemplate template : rubbishList) {
					PropertyFeeOrderTemplateApproverInfo info = new PropertyFeeOrderTemplateApproverInfo();
					info.setApproverId(approverRubbish.getId());
					info.setTemplateId(template.getId());
					ret = propertyFeeOrderTemplateApproverInfoService.save(info);
				}
//
//				for (PropertyFeeOrderTemplate template : rubbishList) {
//					if (estateRoom.getCount() == null) {
//						template.setYouhuiPrice(BigDecimal.valueOf(0.00));
//						ret = propertyFeeOrderTemplateService.updateById(template);
//					}
//				}
			}
			return toAjax(ret);
		}
		return toAjax(0);
	}

	/**
	 * 删除小区内的房屋列信息
	 */
	@ApiOperation("删除小区内的房屋列信息")
	@PreAuthorize("@ss.hasPermi('module:estateRoom:remove')")
	@Log(title = "小区内的房屋列信息", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
	public AjaxResult<Void> remove(@NotEmpty(message = "主键不能为空") @PathVariable Long[] ids) {
		return toAjax(estateRoomService.removeByIds(Arrays.asList(ids)) ? 1 : 0);
	}

	/**
	 * 批量生成消息房屋二维码
	 */
	@ApiOperation("批量生成消息房屋二维码")
	@PreAuthorize("@ss.hasPermi('module:estateRoom:edit')")
	@Log(title = "批量生成消息房屋二维码", businessType = BusinessType.UPDATE)
	@DeleteMapping("/resetQrCodeMulti/{ids}")
	public AjaxResult<Void> resetQrCodeMulti(@NotEmpty(message = "主键不能为空") @PathVariable Long[] ids) {
		int okCount = 0;
		for (Long id : ids) {
			EstateRoom estateRoom = estateRoomService.getById(id);
			if (estateRoom != null) {
				try {
					String fileName = "room_qr_" + estateRoom.getId() + ".jpg";
					String content = "https://www.caihengyun.com/wxmini/room/info?id=" + estateRoom.getId();
					int upload_type = FileUploadUtils.TYPE_ESTATE_ROOM_PHOTOS;
					System.out.println("content:  " + content);
					String img_key = FileUploadUtils.getUploadPrefix(upload_type) + estateRoom.getEstateId() + "/" + fileName;

					QRCodeUtilEx.createQrCodeImg(content, estateRoom.getEstateName() + " " + estateRoom.getRoomNo(), null, uploadPath + "/" + img_key, true, fileName, upload_type);
					estateRoom.setQrCode(img_key);
				} catch (Exception ex) {
					ex.printStackTrace();
				}
				boolean bl = estateRoomService.updateById(estateRoom);
				if (bl) {
					okCount++;
				}
			}
		}
		return AjaxResult.success("共生成成功" + okCount + "个");
	}

	/**
	 * 重置二维码
	 */
	@Log(title = "重置二维码")
	@PostMapping("/resetQrCode")
	@ResponseBody
	@PreAuthorize("@ss.hasPermi('module:estate:edit')")
	public AjaxResult<Void> resetQrCode(@RequestBody EstateRoom estateRoom) {
		if (estateRoom.getId() != null) {
			try {
				estateRoom = estateRoomService.getById(estateRoom.getId());
				String fileName = "room_qr_" + estateRoom.getId() + ".jpg";
				String content = "https://www.caihengyun.com/wxmini/room/info?id=" + estateRoom.getId();
				int upload_type = FileUploadUtils.TYPE_ESTATE_ROOM_PHOTOS;
				System.out.println("content:  " + content);
				String img_key = FileUploadUtils.getUploadPrefix(upload_type) + estateRoom.getEstateId() + "/" + fileName;

				QRCodeUtilEx.createQrCodeImg(content, estateRoom.getEstateName() + " " + estateRoom.getRoomNo(), null, uploadPath + "/" + img_key, true, fileName, upload_type);
				estateRoom.setQrCode(img_key);
			} catch (Exception ex) {
				ex.printStackTrace();
			}
			if (estateRoomService.updateById(estateRoom)) {
				return AjaxResult.success();
			}
		}
		return AjaxResult.error();
	}


	/**
	 * 根据年份生成选中年份的物业费模板
	 */
	@ApiOperation("新增小区内的房屋列信息")
	@PreAuthorize("@ss.hasPermi('module:estateRoom:add')")
	@Log(title = "小区内的房屋列信息", businessType = BusinessType.INSERT)
	@RepeatSubmit
	@PostMapping("/addTempByYear")
	public AjaxResult<Void> addTempByYear(@Validated(AddGroup.class) @RequestBody EstateRoom estateRoom) {

		if (StrUtil.isEmpty(estateRoom.getYear())) {
			return AjaxResult.error("请输入年份");
		}
		if (estateRoom.getEstateId() == null || estateRoom.getEstateId() == 0) {
			return AjaxResult.error("请选择小区");
		}
		int ret = propertyFeeOrderTemplateService.addTemplateByYear(estateRoom.getEstateId(), estateRoom.getYear(), estateRoom.getMonth());
		return toAjax(ret);
	}

	/**
	 * 根据年份生成选中年份的物业费模板
	 */
	@ApiOperation("新增小区内的房屋列信息")
	@PreAuthorize("@ss.hasPermi('module:estateRoom:add')")
	@Log(title = "小区内的房屋列信息", businessType = BusinessType.INSERT)
	@RepeatSubmit
	@PostMapping("/addTempByRoomYear")
	public AjaxResult<Void> addTempByRoomYear(@Validated(AddGroup.class) @RequestBody EstateRoom estateRoom) {

		if (StrUtil.isEmpty(estateRoom.getYear())) {
			return AjaxResult.error("请输入年份");
		}
		if (estateRoom.getId() == null || estateRoom.getId() == 0) {
			return AjaxResult.error("请选择房屋");
		}
		int ret = propertyFeeOrderTemplateService.addTemplateByRoomYear(estateRoom.getId(), estateRoom.getYear(), estateRoom.getMonth());
		return toAjax(ret);
	}

	/**
	 * 通过id查询房屋信息
	 */
	public List<EstateRoom> roomList(Integer id) {
		QueryWrapper<EstateRoom> qw = new QueryWrapper<>();
		qw.eq("id", id);
		List<EstateRoom> list = estateRoomService.list(qw);
		return list;
	}

	/**
	 * 通过房屋信息查询id
	 */
	public List<EstateRoom> roomInfo(Integer estateId, String buildNo, String unitNo, String roomNum) {
		QueryWrapper<EstateRoom> qw = new QueryWrapper<>();
		qw.eq("estate_id", estateId);
		qw.eq("build_no", buildNo);
		qw.eq("unit_no", unitNo);
		qw.eq("room_num", roomNum);
		List<EstateRoom> list = estateRoomService.list(qw);
		return list;
	}

	@ApiOperation("查询小区内本年度欠费的的房屋列信息列表")
	@PreAuthorize("@ss.hasPermi('module:estateRoom:list')")
	@GetMapping("/arrearageList")
	public TableDataInfo<EstateRoom> arrearageList(@Validated EstateRoom estateRoom) {
		LocalDate currentDate = LocalDate.now();
		Month currentMonth = currentDate.getMonth();
		int year = currentDate.getYear();
		int month = currentMonth.getValue();
		QueryWrapper<PropertyFeeOrderTemplate> qw1 = new QueryWrapper<>();
		qw1.eq("year_num", estateRoom.getYear());
		qw1.eq("state", 0);
		qw1.lt("month_num", 12);
		if (estateRoom.getEstateId() != null) {
			qw1.eq("estate_id", estateRoom.getEstateId());
		}
		if (estateRoom.getRealName() != null) {
			qw1.and(wrapper -> {
				wrapper.like("real_name", estateRoom.getRealName())
					.or().like("phone_num", estateRoom.getRealName())
					.or().like("room_no", estateRoom.getRealName());
			});
		}
		qw1.groupBy("room_id");
		List<PropertyFeeOrderTemplate> list1 = propertyFeeOrderTemplateService.list(qw1);
		List<EstateRoom> roomList = new ArrayList<>();
		for (PropertyFeeOrderTemplate list : list1) {
			EstateRoom room = estateRoomService.selectByUniqueColumn("id", list.getRoomId());
			String jiaofei = list.getYearNum() + "年" + list.getMonthNum() + "月";
			room.setJiaofei(jiaofei);
			roomList.add(room);
		}
		return PageUtils.buildDataInfo(roomList);
	}



	/**
	 * 欠费导出
	 */
	@ApiOperation("欠费导出")
	@PreAuthorize("@ss.hasPermi('module:estateRoom:eletrictExport')")
	@Log(title = "小区内的房屋列信息", businessType = BusinessType.EXPORT)
	@GetMapping("/exportArrearage")
	public AjaxResult<EstateRoom> exportArrearage(@Validated EstateRoom estateRoom) {
		LocalDate currentDate = LocalDate.now();
		Month currentMonth = currentDate.getMonth();
		int year = currentDate.getYear();
		int month = currentMonth.getValue();
		Map<String, Object> qw1 = new HashMap<>();
		qw1.put("year_num", 2024);
		qw1.put("month_num", 13);
		if (estateRoom.getEstateId() != null) {
			qw1.put("estate_id", estateRoom.getEstateId());
		}
		if (estateRoom.getBuildId() != null) {
			qw1.put("build_id", estateRoom.getBuildId());
		}
		List<PropertyFeeOrderTemplate> list1 = propertyFeeOrderTemplateService.selectQianfeiList(qw1);
		List<EstateRoom> roomList = new ArrayList<>();
		for (PropertyFeeOrderTemplate list : list1) {
			EstateRoom room = estateRoomService.selectByUniqueColumn("id", list.getRoomId());
			String jiaofei = list.getYearNum() + "年" + list.getMonthNum() + "月";
			room.setJiaofei(jiaofei);
			room.setQianfei(String.valueOf(list.getTotalMoney()));
			roomList.add(room);
		}
		ExcelUtil<EstateRoom> util = new ExcelUtil<>(EstateRoom.class);
		return util.exportExcel(roomList, "小区内的欠费信息");
	}

	/**
	 * 生成小区的假业主信息
	 */
	@ApiOperation("生成小区的假业主信息")
	@PreAuthorize("@ss.hasPermi('module:estateRoom:list')")
	@GetMapping("/shengcheng")
	public TableDataInfo<EstateRoom> shengcheng(@Validated EstateRoom estateRoom) {
		SysUser sysUser = getUser();
		QueryWrapper<EstateRoom> qw = new QueryWrapper<>();

		if (sysUser.getUserType() < 2) {
			if (estateRoom.getEstateId() != null) {
				qw.eq("estate_id", estateRoom.getEstateId());
			}
		} else if (sysUser.getUserType() == 2) {
			if (sysUser.getEstateId() != null && estateRoom.getEstateId() != null) {
				qw.eq("estate_id", sysUser.getEstateId());
			} else if (sysUser.getEstateId() == null && estateRoom.getEstateId() == null) {
				QueryWrapper qwEstate = new QueryWrapper<>();
				qwEstate.eq("property_id", sysUser.getPropertyId());
				List<Estate> estates = estateService.list(qwEstate);
				for (Estate estate : estates) {
					qw.or().eq("estate_id", estate.getId());
				}
			} else if (sysUser.getEstateId() == null && estateRoom.getEstateId() != null) {
				qw.eq("estate_id", estateRoom.getEstateId());
			}
		} else if (sysUser.getUserType() == 3) {
			qw.eq("estate_id", sysUser.getEstateId());
		}
		if (estateRoom.getRoomNum() != null) {
			qw.like("room_num", estateRoom.getRoomNum());
		}
		if (estateRoom.getUnitNo() != null) {
			qw.like("unit_no", estateRoom.getUnitNo());
		}
		if (estateRoom.getBuildNo() != null) {
			qw.like("build_no", estateRoom.getBuildNo());
		}
		if (estateRoom.getRealName() != null) {
			qw.and(wrapper -> {
				wrapper.like("real_name", estateRoom.getRealName())
					.or().like("phone_num", estateRoom.getRealName())
					.or().like("room_no", estateRoom.getRealName());
			});
		}
		qw.orderByAsc("room_no");
		List<EstateRoom> list = estateRoomService.list(qw);
		if (CollUtil.isNotEmpty(list)) {
			for (EstateRoom room : list) {
				if (StrUtil.isNotEmpty(room.getQrCode())) {
					room.setQrCode(imgUrl + room.getQrCode());
				}
				//查询该业主是否已绑定
				QueryWrapper<EstateRoomBangUser> qw1 = new QueryWrapper<>();
				qw1.eq("room_id", room.getId());
				List<EstateRoomBangUser> user = estateRoomBangUserService.list(qw1);
				if (user.size() != 0) {
					continue;
				}
				//根据小区信息添加业主数据
				WxUser wx = new WxUser();
				if (room.getPhoneNum() != null) {
					wx.setPhoneNum(room.getPhoneNum());
				} else {
					continue;
				}
				if (room.getRealName() != null) {
					wx.setPhoneNum(room.getRealName());
				} else {
					continue;
				}
				wx.setPlatform("wxmini");
				boolean t = wxUserService.save(wx);
				if (!t) {
					break;
				}
				EstateRoomBangUser user1 = new EstateRoomBangUser();
				user1.setEstateId(estateRoom.getEstateId());
				user1.setRoomId(room.getId());
				user1.setBangWxUserId(wx.getId());
				t = estateRoomBangUserService.save(user1);
				if (!t) {
					break;
				}
			}
		}

		return null;
	}
}
